package com.common.hibernate.dml;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;

import com.common.bean.PageBean;
import com.common.bean.SearchBean;

/**
 * hibernate查询通用查询类(QBC查询)
 * 
 * @author 孙树林
 * 
 */
public class HibernateQBCQuery extends HibernateDataAccess {

	/**
	 * hibernate QBC通用分页查询(简单查询)
	 * 
	 * @param searchBean
	 * @param clazz
	 * @return map
	 */
	@SuppressWarnings("rawtypes")
	public List criteriaOfSimple(SearchBean searchBean, Class clazz) {
		Criteria criteria = getSession().createCriteria(clazz);
		// 简单的查询条件
		HibernateSentenceHandle hibernateSentenceHandle = new HibernateSentenceHandle();
		hibernateSentenceHandle.addSimpleCriteria(criteria, searchBean.getArgumentsBeans());
		// 返回结果集
		return criteria(criteria, searchBean);
	}

	/**
	 * hibernate QBC通用分页查询(复合查询)
	 * 
	 * @param searchBean
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List criteriaOfComposite(SearchBean searchBean, Class clazz) {
		Criteria criteria = getSession().createCriteria(clazz);
		// 复合查询条件
		HibernateSentenceHandle hibernateSentenceHandle = new HibernateSentenceHandle();
		hibernateSentenceHandle.addCompositeCriteria(criteria, searchBean);
		// 返回结果集
		return criteria(criteria, searchBean);
	}

	/**
	 * 查询
	 * 
	 * @param criteria
	 * @param searchBean
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected List criteria(Criteria criteria, SearchBean searchBean) {
		boolean isPage = searchBean.isPage();
		if (isPage) {
			// 查询分页
			PageBean pageBean = searchBean.getPageBean();
			Long rowCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
			criteria.setFirstResult(pageBean.getStart());
			criteria.setMaxResults(pageBean.getPageSize());
			pageBean.setTotalSize(rowCount.intValue());
			criteria.setProjection(null);
		}
		return criteria.list();
	}
}
